package cn.edu.zafu.bigdata.lhff;

import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class UDPServer {
    public static void main(String[] args) {
        DatagramSocket socket = null;
        try {
            int port = 9876;  // 服务端监听的端口
            socket = new DatagramSocket(port);
            System.out.println("Server is listening on port " + port);

            byte[] receiveData = new byte[1024];  // 用于接收客户端请求的数据包

            while (true) {
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                socket.receive(receivePacket);  // 接收客户端请求

                String clientAddress = receivePacket.getAddress().toString();
                int clientPort = receivePacket.getPort();
                System.out.println("Received request from " + clientAddress + ":" + clientPort);

                // 获取当前服务器时间
                String serverTime = getCurrentTime();

                // 将当前时间发送给客户端
                DatagramPacket sendPacket = new DatagramPacket(
                        serverTime.getBytes(),
                        serverTime.length(),
                        receivePacket.getAddress(),
                        receivePacket.getPort()
                );
                socket.send(sendPacket);
                System.out.println("Sent current time to client: " + serverTime);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket != null && !socket.isClosed()) {
                socket.close();
            }
        }
    }

    // 获取当前时间的字符串（格式化为 "yyyy-MM-dd HH:mm:ss"）
    private static String getCurrentTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date());
    }
}